﻿using System.Linq;
using Telerik.Windows.Controls;
using Telerik.Windows.Controls.GridView;

namespace csla4Skeleton.UI.SL.Resources.Utility
{
    public class GridViewUtil
    {
        public static void SetCurrentCellByValue(RadGridView gridvew, object cellValue)
        {
            GridViewCell cell = GetCellByContent(gridvew, cellValue);
            if (cell != null)
            {
                cell.IsCurrent = true;
                cell.IsSelected = true;
                cell.Focus();
            }
        }

        public static void FocusRow(RadGridView gridvew, int rowIndex)
        {
            if (rowIndex >= 0)
            {
                var item = gridvew.Items[rowIndex];
                gridvew.ScrollIntoViewAsync(item, o =>
                {
                    var row = o as GridViewRow;
                    if (row != null)
                    {
                        row.IsCurrent = true;
                        row.IsSelected = true;
                        row.Focus();
                    }
                });
            }
        }

        public static void FocusLastRow(RadGridView gridvew)
        {
            int rowIndex = gridvew.Items.Count - 1;
            if (rowIndex >= 0)
            {
                var item = gridvew.Items[rowIndex];
                gridvew.ScrollIntoViewAsync(item, o =>
                {
                    var row = o as GridViewRow;
                    if (row != null)
                    {
                        row.IsCurrent = true;
                        row.IsSelected = true;
                        row.Focus();
                    }
                });
            }
        }

        private static GridViewCell GetCellByContent(RadGridView gridvew, object cellValue)
        {
            return
                (from cell in gridvew.ChildrenOfType<GridViewCell>()
                 where cell.Value.ToString() == cellValue.ToString()
                 select cell).LastOrDefault();
        }
    }
}
